# -*- coding: utf-8 -*-
# @Author: ystlong
# @Date:   2017-12-19 06:05:56
# @Last Modified by:   ystlong
# @Last Modified time: 2017-12-23 07:37:45

from HookUtil import ProxyThreadPool
import HookUtil

def patch_header_http_head(header_str, host):
	name = False
	spc = '\r\n'
	s = header_str.split(spc)
	if len(s) < 3:
		spc = '\r'
		s = header_str.split(spc)
	if s[0][:-1].upper().endswith("HTTP/1."):
		# http connect
		http_sp = s[0].split(" ")
		uri_sp = http_sp[1].split("/")
		name = uri_sp[1]
		http_sp[1] = "/" + "/".join(uri_sp[2:])
		s[0] = " ".join(http_sp)
		for i in xrange(len(s)):
			if s[i].upper().startswith("HOST"):
				s[i] = "Host: " + host
				break

		header_str = spc.join(s)
	return (name, header_str)

class HookProxy(object):
	"""docstring for HookProxy"""
	# request_socket 为主动方(浏览器发起方)， response_socket为被动放
	def __init__(self, request_socket, response_socket):
		super(HookProxy, self).__init__()
		self.request_socket = request_socket
		self.response_socket = response_socket
		self.on = True
		self.buffsize = 2048
		
	def _tunnel_socket(self, first_socket, second_socket, patch_handle=None):
		try:
			while self.on:
				data = first_socket.recv(self.buffsize)
				if not data:
					break
				# print "==================="
				# print data
				# print "==================="
				if patch_handle != None:
					data = patch_handle(data)
				second_socket.send(data)
		except Exception as e:
			print(repr(e))
		self.close()

	# 获取request数据写入到response_socket
	def start_request_data(self):
		def runable():
			self._tunnel_socket(self.request_socket, self.response_socket)
		ProxyThreadPool.new_thread(runable)

	def start_response_data(self):
		def runable():
			self._tunnel_socket(self.response_socket, self.request_socket)
		ProxyThreadPool.new_thread(runable)

	def start(self):
		self.start_request_data()
		self.start_response_data()

	def close(self):
		self.on = False
		HookUtil.clean_socket(self.response_socket)
		HookUtil.clean_socket(self.request_socket)
		print "xxxx close"
